/*
 * @Description:
 * @Version:
 * @Author: Troubadour
 * @Date: 2022-10-11 19:07:00
 * @LastEditors: Troubadour
 * @LastEditTime: 2022-10-11 20:36:34
 */

#include "Battery.h"


/* 电池卡尔曼滤波结构体 */
kalmanTypeDef Battery_Kalman = {0};
BatteryTypeDef battery = {0};


/**
 * @function: battery_Read
 * @brief 电池电量读取,数据存储在battery结构体中
 * @param {*}
 * @return {*}
 */
void battery_Read(void)
{
    static uint16_t BatCnt  = 0;

    HAL_ADC_PollForConversion(&hadc1, 100);
    battery.raw = HAL_ADC_GetValue(&hadc1);
#if USE_KALMAN_FILTER
    kalman_Filter(&Battery_Kalman, (double)battery.raw);
    battery.raw = (uint16_t)Battery_Kalman.Out;
#endif
    if(BatCnt < BAT_AVERAGE_FILTER_CNT)
    {
        battery.rawArray[BatCnt++] = battery.raw;
        return;
    }
    else
    {
        uint8_t i = 0;
        uint32_t BatSum = 0;
        for(i = 0; i < BAT_AVERAGE_FILTER_CNT; i++)
        {
            BatSum += battery.rawArray[i];
        }
        battery.raw = (uint16_t)(BatSum / BAT_AVERAGE_FILTER_CNT);
        BatCnt = 0;
    }

    battery.voltge = (float)battery.raw * ADC_RATIO;
    battery.voltge = (battery.voltge + ADC_ERROR_VALUE) / ADC_PARTIAL;

    if(battery.voltge > BAT_VOLTAGE_MAX)
    {
        battery.soc = 100;
    }
    else if(battery.voltge < BAT_VOLTAGE_MIN)
    {
        battery.soc = 0;
    }
    else
    {
        battery.soc = (uint8_t)( (battery.voltge - BAT_VOLTAGE_MIN) / (BAT_VOLTAGE_MAX-BAT_VOLTAGE_MIN) * 100);
    }
}


/**
 * @function: battery_init
 * @brief 电池电量初始化
 * @param {*}
 * @return {*}
 */
void battery_init(void)
{
    // 启动ADC转换
    HAL_ADC_Start(&hadc1);
    HAL_Delay(50);
#if USE_KALMAN_FILTER
    Battery_Kalman.Q = 0.01;
    Battery_Kalman.R = 0.5;
    HAL_ADC_PollForConversion(&hadc1, 100);
    battery.raw = HAL_ADC_GetValue(&hadc1);
    Kalman_init(&Battery_Kalman, (double)battery.raw);
#endif
}

